<template>
	<view class="detail-container">
		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<view>
				<image class="back" src="/static/images/白色左箭头.png" mode="" @click="goBack"></image>
			</view>
			<view style="padding-top: 20rpx; font-size: 18px;">洗车</view>
		</view>

		<!-- 主要内容区 -->
		<view class="content-wrapper">
			<!-- 店铺信息卡片 -->
			<view class="store-card" v-if="merchant">
				<image :src="merchant.img || '/static/user3/car1.jpeg'" mode="aspectFill" class="store-image"></image>
				<view class="store-info">
					<view class="store-name">{{ merchant.name }}</view>
					<view class="rating-row">
						<view class="stars">
							<text v-for="n in 5" :key="n" class="star" :class="{ 'active': n <= merchant.rete }">★</text>
							<text class="rating-score">{{ merchant.rete }}分</text>
						</view>
					</view>
					<view class="business-info">
						<text>营业时间：{{ merchant.startTime }}--{{ merchant.endTime }}</text>
						<view class="location-row">
							<text>位置：{{ merchant.address }}</text>
							<image src="/static/wash/location.png" mode="aspectFit" class="location-icon"></image>
						</view>
					</view>
				</view>
			</view>

			<!-- 服务项目 -->
			<view class="service-section">
				<view class="section-title">服务项目</view>
				<view class="service-options">
					<radio-group class="radio-group" @change="handleServiceChange">
						<label class="radio-item" v-for="(service, index) in services" :key="index">
							<radio :value="String(service.id)" :checked="index === 0" />
							<text>{{ service.name }}</text>
						</label>
					</radio-group>
				</view>

				<view class="price-info" v-if="selectedService">
					<text class="current-price">¥{{ selectedService.presentPrice }}</text>
					<text class="original-price">¥{{ selectedService.originalPrice }}</text>
				</view>

				<view class="service-desc" v-if="selectedService">
					{{ selectedService.introduction }}
				</view>
			</view>

			<!-- 服务评价 -->
			<view class="review-section">
				<view class="section-title">服务评价</view>
				<view class="review-list">
					<view class="review-item" v-for="review in serviceReviews" :key="review.id">
						<view class="reviewer-info">
							<image :src="review.avatar" mode="aspectFill" class="avatar"></image>
							<view class="review-content">
								<text class="reviewer-name">{{ review.user }}</text>
								<view class="stars">
									<text v-for="n in 5" :key="n" class="star"
										:class="{ 'active': n <= review.rate }">★</text>
								</view>
								<text class="review-text">{{ review.text }}</text>
								<view class="review-images" v-if="review.images && review.images.length">
									<image v-for="img in review.images" :key="img" :src="img" mode="aspectFill" class="review-image"></image>
								</view>
							</view>
							<text class="review-date">{{ review.time }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 底部按钮 -->
		<view class="bottom-bar">
			<button class="service-btn" @click="contactService">
				<image src="/static/home/wash/客服@3x.png" mode="aspectFit" class="btn-icon"></image>
				联系客服
			</button>
			<button class="order-btn" @click="goEnterOrder">立即下单</button>
		</view>

		<!-- 客服弹出层 -->
		<uni-popup ref="servicePopup" type="bottom">
			<view class="service-popup">
				<view class="service-number">{{ merchant?.phone || '暂无联系方式' }}</view>
				<view class="action-buttons">
					<button class="action-btn copy-btn" @click="copyPhoneNumber">复制</button>
					<button class="action-btn cancel-btn" @click="closeServicePopup">取消</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

const merchant = ref(null);
const services = ref([]);
const selectedService = ref(null);
const servicePopup = ref(null);
const serviceReviews = ref([]);

// 获取用户信息
const fetchUserInfo = async (userId) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: `http://localhost:9402/user/${userId}`,
			method: 'GET',
			header: {
				'Authorization': uni.getStorageSync('Token')
			},
			success: (res) => {
				if (res.data.code === 200 && res.data.data) {
					resolve(res.data.data);
				} else {
					reject(new Error(res.data.msg || '获取用户信息失败'));
				}
			},
			fail: (error) => {
				reject(error);
			}
		});
	});
};

// 获取服务评价
const fetchServiceReviews = async (merchantId) => {
	uni.request({
		url: `http://localhost:9401/orders/evaluations/${merchantId}`,
		method: 'GET',
		header: {
			'Authorization': uni.getStorageSync('Token')
		},
		success: async (res) => {
			if (res.data.code === 200 && res.data.data) {
				// 使用 Promise.all 并行获取所有用户信息
				const reviewsWithUserInfo = await Promise.all(
					res.data.data.map(async (review) => {
						try {
							const userInfo = await fetchUserInfo(review.userId);
							return {
								user: userInfo.userName ? userInfo.userName.substring(0, 1) + '**' : '匿名用户',
								avatar: userInfo.avatar || '/static/whb/youhui2.jpg',
								rate: review.rate,
								time: review.time,
								text: review.content,
								images: review.imgs ? review.imgs.split(',') : [],
								id: review.userId
							};
						} catch (error) {
							console.error('获取用户信息失败:', error);
							return {
								user: '匿名用户',
								avatar: '/static/whb/youhui2.jpg',
								rate: review.rate,
								time: review.time,
								text: review.content,
								images: review.imgs ? review.imgs.split(',') : [],
								id: review.userId
							};
						}
					})
				);
				serviceReviews.value = reviewsWithUserInfo;
			} else {
				uni.showToast({
					title: res.data.msg || '获取服务评价失败',
					icon: 'none'
				});
			}
		},
		fail: (error) => {
			console.error('获取服务评价失败:', error);
			uni.showToast({
				title: '网络请求失败，请重试',
				icon: 'none'
			});
		}
	});
};

// 获取商户详情
const fetchMerchantDetails = (id) => {
	uni.request({
		url: `http://localhost:9401/merchant/${id}`,
		method: 'GET',
		header: {
			'Authorization': uni.getStorageSync('Token')
		},
		success: (res) => {
			// console.log('商户详情:', res);
			if (res.data.code === 200 && res.data.data) {
				merchant.value = res.data.data;
				// 获取服务列表
				fetchServices(id);
				// 获取服务评价
				fetchServiceReviews(id);
			} else {
				uni.showToast({
					title: res.data.msg || '获取商户详细信息失败',
					icon: 'none'
				});
			}
		},
		fail: (error) => {
			console.error('获取商户详细信息失败:', error);
			uni.showToast({
				title: '网络请求失败，请重试',
				icon: 'none'
			});
		}
	});
};

// 获取服务列表
const fetchServices = (merchantId) => {
	uni.request({
		url: 'http://localhost:9401/fuwudetails/byMerchantAndType',
		method: 'GET',
		data: {
			merchantId: merchantId,
			typeId: 3,
			pageNum: 1,
			pageSize: 10
		},
		header: {
			'Authorization': uni.getStorageSync('Token')
		},
		success: (res) => {
			// console.log('服务列表:', res);
			if (res.data.code === 200 && res.data.rows) {
				services.value = res.data.rows.map(service => ({
					id: service.id,
					name: service.name,
					presentPrice: service.presentPrice,
					originalPrice: service.originalPrice,
					introduction: service.introduction || '暂无描述'
				}));
				if (services.value.length > 0) {
					selectedService.value = services.value[0];
				} else {
					uni.showToast({
						title: '暂无服务项目',
						icon: 'none'
					});
				}
			} else {
				uni.showToast({
					title: res.data.msg || '获取服务列表失败',
					icon: 'none'
				});
			}
		},
		fail: (error) => {
			console.error('获取服务列表失败:', error);
			uni.showToast({
				title: '网络请求失败，请重试',
				icon: 'none'
			});
		}
	});
};

// 服务选择变化
const handleServiceChange = (e) => {
	const serviceId = e.detail.value;
	selectedService.value = services.value.find(s => s.id === parseInt(serviceId));
};

const goBack = () => {
	uni.navigateBack();
};

const goEnterOrder = () => {
	if (!selectedService.value) {
		uni.showToast({
			title: '请选择服务项目',
			icon: 'none'
		});
		return;
	}
	
	if (!merchant.value || !merchant.value.id) {
		uni.showToast({
			title: '商户信息不完整',
			icon: 'none'
		});
		return;
	}

	uni.navigateTo({
		url: `/pages/index/xiche/xichedetail/enterorder/enterorder?merchantId=${merchant.value.id}&serviceId=${selectedService.value.id}`
	});
};

// 显示客服弹出层
const showServicePopup = () => {
	servicePopup.value.open();
};

// 关闭客服弹出层
const closeServicePopup = () => {
	servicePopup.value.close();
};

// 复制电话号码
const copyPhoneNumber = () => {
	if (!merchant.value?.phone) {
		uni.showToast({
			title: '暂无联系方式',
			icon: 'none'
		});
		return;
	}
	uni.setClipboardData({
		data: merchant.value.phone,
		success: () => {
			uni.showToast({
				title: '复制成功',
				icon: 'success'
			});
			closeServicePopup();
		}
	});
};

// 联系客服
const contactService = () => {
	showServicePopup();
};

// 页面加载时获取商户详情
onLoad((options) => {
	if (options && options.id) {
		fetchMerchantDetails(options.id);
	} else {
		uni.showToast({
			title: '商户ID不存在',
			icon: 'none'
		});
		setTimeout(() => {
			goBack();
		}, 1500);
	}
});
</script>

<style scoped>
	.detail-container {
		min-height: 100vh;
		padding-bottom: 120rpx;
	}

	.nav-bar {
		text-align: center;
		height: 288rpx;
		padding: 0 30rpx;
		color: #fff;
		background: #4080FF;
	}

	.nav-bar .back {
		position: absolute;
		left: 16px;
		top: 16px;
		width: 15px;
		height: 15px;
		z-index: 2;
	}

	.content-wrapper {
		padding: 20rpx;
		margin-top: -200rpx;
		min-height: calc(100vh - 88rpx);
		padding-bottom: 120rpx;
	}

	.store-card {
		background: #FFFFFF;
		border-radius: 20rpx;
		margin-bottom: 20rpx;
	}

	.store-image {
		width: 100%;
		height: 400rpx;
		border-radius: 10px;
	}

	.store-info {
		padding: 20rpx;
	}

	.store-name {
		font-size: 32rpx;
		font-weight: 500;
		margin-bottom: 16rpx;
	}

	.rating-row {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.stars {
		display: flex;
		align-items: center;
	}

	.star {
		color: #DDDDDD;
		font-size: 24rpx;
	}

	.star.active {
		color: #FFB800;
	}

	.rating-score {
		margin-left: 8rpx;
		font-size: 24rpx;
	}

	.sales {
		margin-left: 20rpx;
		font-size: 24rpx;
		color: #999;
	}

	.business-info {
		font-size: 24rpx;
		color: #666;
		line-height: 1.6;
	}

	.location-row {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.location-icon {
		width: 32rpx;
		height: 32rpx;
	}

	.service-section {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: 500;
		margin-bottom: 20rpx;
	}

	.radio-group {
		display: flex;
		flex-wrap: wrap;
		gap: 20rpx;
	}

	.radio-item {
		display: flex;
		align-items: center;
		gap: 8rpx;
		font-size: 28rpx;
	}

	.price-info {
		margin: 20rpx 0;
	}

	.current-price {
		color: #FF5252;
		font-size: 36rpx;
		font-weight: 500;
	}

	.original-price {
		color: #999;
		font-size: 24rpx;
		text-decoration: line-through;
		margin-left: 10rpx;
	}

	.service-desc {
		font-size: 24rpx;
		color: #666;
		line-height: 1.6;
	}

	.review-section {
		background: #FFFFFF;
		border-radius: 20rpx;
		padding: 20rpx;
		margin-bottom: 20rpx;
	}

	.review-list {
		padding: 0 20rpx;
	}

	.review-item {
		padding: 20rpx 0;
		border-bottom: 1rpx solid #EEEEEE;
	}

	.review-item:last-child {
		border-bottom: none;
	}

	.reviewer-info {
		display: flex;
		gap: 16rpx;
		align-items: flex-start;
	}

	.avatar {
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		flex-shrink: 0;
	}

	.review-content {
		flex: 1;
		min-width: 0;
	}

	.reviewer-name {
		font-size: 28rpx;
		color: #333;
		margin-bottom: 8rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.stars {
		display: flex;
		align-items: center;
		margin: 8rpx 0;
	}

	.star {
		color: #DDDDDD;
		font-size: 24rpx;
	}

	.star.active {
		color: #FFB800;
	}

	.review-text {
		font-size: 26rpx;
		color: #666;
		line-height: 1.6;
	}

	.review-date {
		font-size: 24rpx;
		color: #999;
		margin-left: 16rpx;
		white-space: nowrap;
	}

	.review-images {
		display: flex;
		gap: 10rpx;
		margin-top: 10rpx;
	}

	.review-image {
		width: 150rpx;
		height: 150rpx;
		border-radius: 10rpx;
		object-fit: cover;
	}

	.bottom-bar {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		height: 100rpx;
		background: #FFFFFF;
		display: flex;
		align-items: center;
		padding: 20rpx;
		box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
		z-index: 10;
	}

	.service-btn {
		flex: 1;
		height: 80rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		background: #FFFFFF;
		border: 2rpx solid #4080FF;
		color: #4080FF;
		font-size: 28rpx;
		margin-right: 20rpx;
		border-radius: 40rpx;
	}

	.btn-icon {
		width: 32rpx;
		height: 32rpx;
		margin-right: 8rpx;
	}

	.order-btn {
		flex: 1;
		height: 80rpx;
		background: #4080FF;
		color: #FFFFFF;
		font-size: 28rpx;
		border-radius: 40rpx;
	}

	/* 客服弹出层样式 */
	.service-popup {
		background-color: #FFFFFF;
		padding: 40rpx;
		border-radius: 20rpx 20rpx 0 0;
	}

	.service-number {
		text-align: center;
		font-size: 40rpx;
		color: #333;
		margin-bottom: 40rpx;
	}

	.action-buttons {
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.action-btn {
		width: 100%;
		height: 90rpx;
		line-height: 90rpx;
		text-align: center;
		border-radius: 45rpx;
		font-size: 32rpx;
		border: none;
	}

	.copy-btn {
		background: #4080FF;
		color: #FFFFFF;
	}

	.cancel-btn {
		background: #F5F5F5;
		color: #333;
	}
</style>

